import React, { useEffect, useState } from 'react';
import { Input, Form, Row, Col, Button, Table, Tabs, Tree, Select, message, Alert, Modal } from 'antd';
import { connect, useDispatch } from 'umi';
import { InfoCircleOutlined } from '@ant-design/icons';
// import PageTopFormContent from '../../../components/PageTopFormContent';
import PaginationCommon from '@/components/PaginationCommon';

import styles from './ResManage.less';
import AddAuth from './addAuth/AddAuth';

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const { TabPane } = Tabs;
const { Search } = Input;
const { confirm } = Modal;

const ResManage = (props) => {
  const { resModel, loading: { effects }} = props;
  const { resList, resTotal } = resModel;
  const [form] = Form.useForm();
  const dispatch = useDispatch();

  const [menuList, setMenuList] = useState([]);
  const [dataList] = useState([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentPageNum, setCurrentPageNum] = useState(1);
  const [currentPageSize, setCurrentPageSize] = useState(10);
  const [formData, setFormData] = useState({});
  const [getRoleListData, setGetRoleListData] = useState([]);

  const [sort, setSort] = useState();

  // 菜单树
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [defaultSelectedKeys, setDefaultSelectedKeys] = useState([]); // 默认选中父节点
  const [checkTreeKey, setCheckTreeKey] = useState([]);

  const onExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys);
    setAutoExpandParent(false);
  };

  const generateList = (data) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key, title } = node;
      dataList.push({ key, title });
      if (node.children) {
        generateList(node.children);
      }
    }
  };

  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  const onSearch = (e) => {
    const { value } = e.target;
    const expandedKeys = dataList.length > 0 ? dataList.map((item) => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, menuList);
      }
      return null;
    }).filter((item, i, self) => item && self.indexOf(item) === i) : [];
    setExpandedKeys(expandedKeys);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  const loop = data =>
    data.length > 0 ? data.map((item) => {
      const index = item.title.indexOf(searchValue);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchValue.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span style={{ color: '#f50' }}>{searchValue}</span>
            {afterStr}
          </span>
        ) : (
          <span>{item.title}</span>
        );
      if (item.children) {
        return { title, key: item.key, children: loop(item.children) };
      }

      return {
        title,
        key: item.key,
      };
    }) : [];

  // 查询操作
  const handleSearch = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const param = { ...values };
      setFormData(param);
      setCurrentPageNum(1);
    });
  };

  const handleReset = () => {
    form.resetFields();
    setCurrentPageNum(1);
    setFormData({});
  };

  // 获取菜单列表
  const getMenuList = () => {
    dispatch({
      type: 'resModel/getMenuList',
      payload: {},
    }).then((res) => {
      const { code, data, message: errMsg } = res;
      if (code === 0 && data) {
        const dataListParse = JSON.parse(JSON.stringify(data).replace(/id/g, 'key')
          .replace(/resourceName/g, 'title')
          .replace(/childList/g, 'children'));
        if (Array.isArray(dataListParse)) {
          setDefaultSelectedKeys([dataListParse[0].key]);
          setMenuList(dataListParse);
          generateList(dataListParse);
        }
      } else {
        message.error(errMsg);
      }
    });
  };

  const getResList = () => {
    const submitData = {
      pageIndex: currentPageNum,
      pageSize: currentPageSize,
      ...formData,
      resourceId: checkTreeKey.length > 0 ? Number(checkTreeKey.toString()) : Number(defaultSelectedKeys.toString()),
      sortMap: sort,
    };
    dispatch({
      type: 'resModel/getResList',
      payload: submitData,
    });
  };

  const onSelectTreeChange = (checkTreeKey, allNode) => {
    setCheckTreeKey(checkTreeKey);
  };

  useEffect(() => {
    getMenuList();
  }, []);

  useEffect(() => {
    if (defaultSelectedKeys.length > 0) getResList();
  }, [defaultSelectedKeys, checkTreeKey, currentPageNum, currentPageSize, formData, sort]);

  const addAuth = () => {
    setDrawerVisible(true);
    dispatch({
      type: 'resModel/getRoleList',
      payload: {},
    }).then((res) => {
      const { code, data, message: errMsg } = res;
      if (code === 0) {
        setGetRoleListData(data);
      } else {
        message.error(errMsg);
      }
    });
  };

  const handleCloseDrawer = (bool = false) => {
    setDrawerVisible(false);
    if (bool) {
      handleSearch();
    }
  };

  const handleCancelAuth = (record) => {
    const resourceId = checkTreeKey.length > 0 ? Number(checkTreeKey.toString()) : Number(defaultSelectedKeys.toString());
    confirm({
      title: '确认删除',
      icon: <InfoCircleOutlined style={{ color: '#1890ff' }} />,
      content: '请确认是否收回授权该角色访问菜单的权限!!!',
      onOk() {
        dispatch({
          type: 'resModel/cancelAuth',
          payload: {
            resourceId,
            roleId: record.roleId,
          },
        }).then((res) => {
          const { code, message: errMsg } = res;
          if (code === 0) {
            message.success('您己成功收回授权该角色访问菜单的权限!!!');
            handleSearch();
          } else {
            message.error(errMsg);
          }
        });
      },
    });
  };

  const handleTableChange = (_, filters, sorter) => {
    if (JSON.stringify(sorter) !== '{}') {
      const { field, order } = sorter;
      setSort({ [`t1.${field}`]: order === 'ascend' ? 'asc' : 'desc' });
    }
  };

  const callback = (key) => {
    // console.log(key);
  };

  const handlePaginationChange = (page, pageSize) => {
    setCurrentPageNum(page);
    setCurrentPageSize(pageSize);
  };

  const menuColumns = [
    {
      title: '授权角色',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '用户账号',
      dataIndex: 'users',
      key: 'users',
      ellipsis: true,
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      key: 'gmtModified',
      sorter: true,
      // sorter: (a, b) => a.length - b.length,
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <div>
          <a onClick={() => { handleCancelAuth(record); }}>取消授权</a>
        </div>
      ),
    },
  ];

  const dataColumns = [
    {
      title: '资源编码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '资源名称',
      dataIndex: 'resourceName',
      key: 'resourceName',
    },
    {
      title: '资源类型',
      dataIndex: 'authRole',
      key: 'authRole',
    },
    {
      title: '授权对象',
      dataIndex: 'authUser',
      key: 'authUser',
    },
    {
      title: '更新人',
      dataIndex: 'updater',
      key: 'updater',
    },
    {
      title: '最后一次修改时间',
      dataIndex: 'updataTime',
      key: 'updataTime',
      sorter: (a, b) => a.length - b.length,
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <div>
          <a>授权管理</a>
        </div>
      ),
    },
  ];

  return (
    <div className={styles.root}>
      <div className={styles.tableWapper}>
        <Tabs onChange={callback} type="card" style={{ width: '100%' }}>
          <TabPane tab="菜单" key="1" style={{minHeight:450}}>
            <div className={styles.tabPane}>
              <div className={styles.leftWapper}>
                <Search
                  style={{ marginBottom: 8 }}
                  placeholder="请输入"
                  onChange={onSearch}
                />
                {
                  menuList.length > 0
                    ? (
                      <Tree
                        onExpand={onExpand}
                        expandedKeys={expandedKeys}
                        autoExpandParent={autoExpandParent}
                        treeData={loop(menuList)}
                        onSelect={onSelectTreeChange}
                        defaultSelectedKeys={defaultSelectedKeys}
                      />
                    ) : null
                }
              </div>
              <div className={styles.rightWapper}>
                <Form {...layout} form={form} name="advanced_search">
                  <Row gutter={[24, 2]}>
                    <Col className="gutter-row" span={7}>
                      <Form.Item name="userAccount" label="用户账号">
                        <Input placeholder="请输入用户账号" />
                      </Form.Item>
                    </Col>
                    <Col className="gutter-row" span={7}>
                      <Form.Item name="roleName" label="角色名称">
                        <Input placeholder="请输入角色名称" />
                      </Form.Item>
                    </Col>
                    <Col className="gutter-row" span={10}>
                      <Form.Item noStyle>
                        <Button type="primary" style={{ marginLeft: 15 }} onClick={handleSearch}>
                          查询
                        </Button>
                        <Button style={{ marginLeft: 20 }} onClick={handleReset}>
                          重置
                        </Button>
                        <Button style={{ marginLeft: 20 }} onClick={addAuth}>
                          新增
                        </Button>
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
                <div className={styles.listTable}>
                  <Table
                    columns={menuColumns}
                    dataSource={resList}
                    loading={effects['resModel/getResList']}
                    pagination={false}
                    onChange={handleTableChange}
                  />
                  <PaginationCommon
                    style={{ textAlign: 'right' }}
                    total={resTotal}
                    current={currentPageNum}
                    pageSize={currentPageSize}
                    onChange={handlePaginationChange}
                  />
                </div>
              </div>
            </div>
          </TabPane>
          <TabPane tab="数据" key="2">
            <Alert message="配置除创建人外数据资源的管理权限，提供三种不同类型的授权类型。" type="info" showIcon style={{ marginBottom: 15 }} />
            <div style={{ height: 'inherit' }}>
              <Form {...layout} form={form} name="advanced_search">
                <Row gutter={[24, 2]}>
                  <Col className="gutter-row" span={5}>
                    <Form.Item name="updater" label="资源编码">
                      <Input placeholder="请输入" />
                    </Form.Item>
                  </Col>
                  <Col className="gutter-row" span={5}>
                    <Form.Item name="code" label="资源名称">
                      <Input placeholder="请输入" />
                    </Form.Item>
                  </Col>
                  <Col className="gutter-row" span={5}>
                    <Form.Item name="code" label="资源类型">
                      <Select placeholder="请选择" />
                    </Form.Item>
                  </Col>
                  <Col className="gutter-row" span={9}>
                    <Form.Item wrapperCol={{ ...layout.wrapperCol }}>
                      <Button type="primary">
                        授权
                      </Button>
                      <Button type="primary" style={{ marginLeft: 10 }} onClick={handleSearch}>
                        查询
                      </Button>
                      <Button style={{ marginLeft: 10 }} onClick={handleReset}>
                        重置
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
              <div className={styles.tabPaneData}>
                <Table
                  columns={dataColumns}
                  dataSource={[]}
                  pagination={false}
                />
                <PaginationCommon style={{ textAlign: 'right' }} />
              </div>
            </div>
          </TabPane>
        </Tabs>
      </div>
      {
        drawerVisible && (
          <AddAuth
            defaultSelectedKeys={defaultSelectedKeys}
            checkTreeKey={checkTreeKey}
            getRoleListData={getRoleListData}
            handleCloseDrawer={handleCloseDrawer}
          />
        )
      }
    </div>
  );
};

export default connect(state => state)(ResManage);

